package engine.net;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
import mainpackage.Constant;
import mainpackage.GameBean;
import mainpackage.MainCanvas;
import mainpackage.MainLogic;
import mainpackage.Rms;
import mainpackage.Tools;
import ui.UiInterFace;

/**
 * <p>Title: 网络消息处理类</p>
 * <p>Description: 主要负责联网操作，收发网络消息</p>
 * <p>Copyright: Copyright (c) 2010</p>
 * <p>Company: </p>
 * @author hlw
 * @version 1.0
 */
public class NetManager extends Thread {
    //测试用记录信息

    public int i_sendMsgId = -1;
    //发送流
    private DataInputStream sendIn;
    private DataOutputStream sendOut;
    //发送连接
    private SocketConnection socketSend;
    //网络接收数据包
    byte[] receiveData;
    //网络连接线程停止
    public boolean stopConnect;
    //本类单例
    public static NetManager instance;
    //最大重发次数
    public final static byte RESEND_MAX_NUMS = 2;
    //消息体长度
    private int iNetMsgLen;
    //消息序号
    public static int iNetMsgSerialNumber = 0;
    //超长消息体数据分组长度
    private int iDataGroupLen;
    //超长消息体缓冲
    ByteArrayOutputStream bOut;
    DataOutputStream dOut;
    //接收消息时间计时器检测是否超时用
    public static long lStartReceiveTime = -1;
    //网络线程收发是否异常需要重联,停止收发
    public static boolean blUnUsed;
    //网络重联结束标志,可以发送数据
    public boolean blInitNetManager;
    public static boolean bQuickIntoGame = false;

    /**
     * 创建本类实例
     * @return NetManager
     */
    public static NetManager getInstance() {
        if (instance == null) {
            instance = new NetManager();
        }
        return instance;
    }

    /**
     * 创建新实例
     * @return NetManager
     */
    public static NetManager getNewInstance() {
        if (instance != null) {
            instance.closeConnect();
        }
        instance = null;
        instance = new NetManager();
        return instance;
    }

    public static NetManager checkInstance() {
        return instance;
    }

    /**
     * 启动网络收发线程
     */
    public void startNetManager() {
        this.blUnUsed = false;
        this.blInitNetManager = false;
        this.stopConnect = false;
        this.lStartReceiveTime = -1;
        this.start();
    }

    /**
     * 关闭网络连接清理资源
     */
    public void closeConnect() {
        try {
            Tools.printLog("关闭连接closeConnect");
            this.stopConnect = true;
            this.blUnUsed = true;
            if (this.sendIn != null) {
                this.sendIn.close();
//                sendIn = null;
            }
            if (this.sendOut != null) {
                this.sendOut.close();
//                sendOut = null;
            }
            if (this.socketSend != null) {
                this.socketSend.close();
            }
            if (this.bOut != null) {
                this.bOut.close();
            }
            if (this.dOut != null) {
                this.dOut.close();
            }
            this.sendIn = null;
            this.sendOut = null;
            this.socketSend = null;
            this.receiveData = null;
            this.bOut = null;
            this.dOut = null;
        } catch (Exception ex) {
            if (Constant.DEBUG) {
                ex.printStackTrace();
            }
//            if(Constant.DEBUG)MainCanvas.addLog("网络类closeConnect方法出错！" + ex.toString());
        }
    }

    /**
     * 关闭网络连接准备重联
     */
    public void closeRSConnect() {
        try {
            Tools.printLog("链接关闭closeRSConnect");
            if (this.sendIn != null) {
                this.sendIn.close();
            }
            if (this.sendOut != null) {
                this.sendOut.close();
            }
            if (this.socketSend != null) {
                this.socketSend.close();
            }
            if (this.bOut != null) {
                this.bOut.close();
            }
            if (this.dOut != null) {
                this.dOut.close();
            }
        } catch (Exception ex) {
            if (Constant.DEBUG) {
                ex.printStackTrace();
            }
//            if(Constant.DEBUG)MainCanvas.addLog("网络类closeRSConnect方法出错！" + ex.toString());
        }
        try {
            Thread.currentThread().sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 建立发送连接
     * @param url String 服务器ip地址
     * @return boolean 连接是否成功
     */
    public boolean createSendConnect(String url) {
//        if (Constant.DEBUG) {
//            MainCanvas.pushCallStack("createSendConnect()");
//        }
        Tools.printLog("建立网络连接");
        if (Constant.DEBUG) {
            MainCanvas.addLog("NetManager类网络建立发送连接中！");
        }
        try {
            //建立发送连接
            this.socketSend = (SocketConnection) Connector.open(url);
            this.socketSend.setSocketOption(SocketConnection.DELAY, Constant.SOCKET_DELAY);
            this.socketSend.setSocketOption(SocketConnection.KEEPALIVE, Constant.SOCKET_KEEPALIVE);
            this.socketSend.setSocketOption(SocketConnection.LINGER, Constant.SOCKET_LINGER);
            //#if NOKIA_S40V3 || NORMAL_240_400 || MOTO || K790
//# //             this.socketSend.setSocketOption(SocketConnection.RCVBUF, 7000);
//#             this.socketSend.setSocketOption(SocketConnection.RCVBUF, Constant.SOCKET_RCVBUF);
//#             this.socketSend.setSocketOption(SocketConnection.SNDBUF, Constant.SOCKET_SNDBUF);
            //#else
            this.socketSend.setSocketOption(SocketConnection.RCVBUF, Constant.SOCKET_RCVBUF);
            this.socketSend.setSocketOption(SocketConnection.SNDBUF, Constant.SOCKET_SNDBUF);
            //#endif
            //打开发送流
            this.sendOut = this.socketSend.openDataOutputStream();
            this.sendIn = this.socketSend.openDataInputStream();
            //MainLogic.getInstance().uiInterFace.setGameUiState((byte) 1);
            //发送连接验证消息: 消息数量(i)＋id(i)＋长度(i)＋消息数据(b)(1发送连接2接收连接)
            //封装消息体
//            ByteArrayOutputStream byOutData = new ByteArrayOutputStream();
//            DataOutputStream dOutData = new DataOutputStream(byOutData);
//            dOutData.writeInt(1);
//            dOutData.writeInt(Constant.MSG_NET_CONNECT_AFFIRM);
//            dOutData.writeInt(1);
//            dOutData.writeByte(1);
//            dOutData.flush();
//            byte[] byMsg = byOutData.toByteArray();
//            //封装消息包
//            this.bOut = new ByteArrayOutputStream();
//            this.dOut = new DataOutputStream(this.bOut);
//            //写入帐号id
////            this.dOut.writeInt(Logic.getInstance().player.iAccountId);
//            //写入角色id
////            this.dOut.writeInt(Logic.getInstance().player.iRoleId);
//            //写入消息序号
//            this.dOut.writeInt(this.iNetMsgSerialNumber++);
//            //写入消息体长度
//            this.dOut.writeInt(byMsg.length);
//            //写入消息体
//            this.dOut.write(byMsg);
//            this.dOut.flush();
//            byte[] sendData = this.bOut.toByteArray();
//            //发送数据
//            this.sendOut.write(sendData);
//            this.sendOut.flush();
//            //关闭临时数据缓冲
//            dOutData.close();
//            byOutData.close();
//            dOutData = null;
//            byOutData = null;
//            this.dOut.close();
//            this.bOut.close();
//            this.dOut = null;
//            this.bOut = null;
//            byMsg = null;
//            sendData = null;
//            try
//            {
//                Thread.currentThread().sleep(1000);
//            }
//            catch(Exception e){}
            //接收服务器验证消息:帐号id(i)+角色id(i)+消息序号(i)+消息长度(i)+消息体数量(i)+消息id(i)+长度(i)+状态码(b)
            //读取消息头
//            int iCurPos = 0;
//            byte[] headData = new byte[4];
//            while (iCurPos < 4)
//            {
//                int len = this.sendIn.read(headData, iCurPos, 4 - iCurPos);
//                if (len > 0) iCurPos += len;
//            }
//            int iMsgLen = (int)(((headData[0] & 0xff) << 24) | ((headData[1] & 0xff) << 16) |
//                                ((headData[2] & 0xff) << 8) | (headData[3] & 0xff));
//            if(iMsgLen > 0)
//            {
//                iCurPos = 0;
//                byte[] bodyData = new byte[iMsgLen];
//                while (iCurPos < iMsgLen)
//                {
//                    int len = this.sendIn.read(bodyData, iCurPos, iMsgLen - iCurPos);
//                    if (len > 0) iCurPos += len;
//                }
//                ByteArrayInputStream byIn = new ByteArrayInputStream(bodyData);
//                DataInputStream daIn = new DataInputStream(byIn);
//                daIn.readInt();
//                int iMsgId = daIn.readInt();
//                daIn.readInt();
//                byte byStateCode = daIn.readByte();
//                //验证
////                if(iMsgId != Constant.MSG_NET_CONNECT_AFFIRM || byStateCode != 0)
////                    return false;
//            }
//            else
//            {
//                if(Constant.DEBUG)MainCanvas.addLog("读取消息头错误,长度:"+iMsgLen);
//                return false;
//            }
        } catch (Exception e) {
            e.printStackTrace();
            if (Constant.DEBUG) {
                MainCanvas.addLog("NetManager类网络发送连接处理出错！" + e.toString());
            }
            try {
                Tools.printLog("关闭连接createSendConnect");
                //MainLogic.getInstance().uiInterFace.setGameUiState((byte) 2);
                if (this.socketSend != null) {
                    this.socketSend.close();
                }
                if (this.sendIn != null) {
                    this.sendIn.close();
                }
                if (this.sendOut != null) {
                    this.sendOut.close();
                }
                this.socketSend = null;
                this.sendIn = null;
                this.sendOut = null;
                this.blUnUsed = true;
//                MainLogic.getInstance().exitGame();
//                UiInterFace.sysMessage.showMessage("提示", "连接错误请检查网络！");
                Tools.quitToSetNetConnect();
            } catch (Exception ex1) {
                ex1.printStackTrace();
//                Tools.printLog("建立异常");
                Tools.quitToSetNetConnect();
            }
            return false;
        }
        if (Constant.DEBUG) {
            MainCanvas.popCallStack();
        }
        if (Constant.DEBUG) {
            MainCanvas.addLog("NetManager类网络发送连接建立成功！");
        }
        return true;
    }
    /**
     * 读取消息包长度
     * @return int 消息包长度
     */
    private int socketCloseCount = 0;
    private int iCurPos = 0;

    private int readFbyteHead() throws Exception {
        int iCurPos = 0;
        try {
            if (this.sendIn == null) {
                return -1;
            }
            byte[] headData = new byte[4];
            while (iCurPos < 4) {
                int len = this.sendIn.read(headData, iCurPos, 4 - iCurPos);
                if (len > 0) {
                    iCurPos += len;
                }
            }
            int msgLen = (int) (((headData[0] & 0xff) << 24) | ((headData[1] & 0xff) << 16)
                    | ((headData[2] & 0xff) << 8) | (headData[3] & 0xff));
            headData = null;
            return msgLen;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
    /**
     * 接收数据(针对nokia机型设计)
     * @throws Exception
     */
    //RES – 资源 1  LOG--- 逻辑 2  DB --- 数据库 …3
    public static int testNums = 0;
    public static int testMsid = 0;
    public static int testMsid2 = 0;

    public void receive2() throws Exception {
        //异常情况下不接收数据
        if (this.blUnUsed) {
            return;
        }
        if (this.sendIn == null) {
            return;
        }
        
        int msgId = -1;
        byte msgType = -1;
//        try {
        //消息包长度
        int iMsgLen = this.readFbyteHead();

        //消息序号
        this.readFbyteHead();
        testNums += 1;
//        Tools.printLog("receive message count:"+ testNums);
//             this.iNetMsgSerialNumber =
//         Tools.printLog("receive2:iNetMsgSerialNumber" + iNetMsgSerialNumber);
        //消息类型
        msgType = this.sendIn.readByte();
        if (msgType == Constant.SOCKET_MSG_TYPE_HEART) {
            long ttmp = System.currentTimeMillis() + MainLogic.lCSSpaceTime;
            //客户端时间
            long lclienttime = this.sendIn.readLong();
            //服务器时间
            MainLogic.lServerCurrentTime = this.sendIn.readLong();
//               Tools.printLog("client time is: " + lclienttime );
            if (MainLogic.lGSOrigDelta == 0) {
                MainLogic.lGSOrigDelta = MainLogic.lServerCurrentTime - ttmp;
            }
            int delta_t = (int) (ttmp - lclienttime);
            MainLogic.getInstance().setDelayTime(delta_t / 2);
//               Tools.printLog("correctedDelta time is "+ MainLogic.lCSDelayTime );
            MainLogic.lCSSpaceTime = MainLogic.lGSOrigDelta + MainLogic.lCSDelayTime;
            return;
        }
        //消息id
        msgId = this.readFbyteHead();
        if (Constant.DEBUG) {
            if (msgId != 143) {
                MainCanvas.addLog("receive:" + msgId);

            }
        }
        testMsid2 = msgId;
//        Tools.printLog("recevieMsg:" + msgId);
        //总长度减去包头长度 = 数据长度
        iMsgLen -= Constant.SOCKET_HEAD_LENGTH;
        byte[] bodyData = null;
        if (iMsgLen > 0 && iMsgLen < 200000) {
            int iCurPos = 0;
            bodyData = new byte[iMsgLen];
            while (iCurPos < iMsgLen) {
                int len = this.sendIn.read(bodyData, iCurPos, iMsgLen - iCurPos);
                if (len > 0) {
                    iCurPos += len;
                }
            }
            //得到消息体
            this.receiveData = bodyData;
        } else {
            if (Constant.DEBUG) {
                MainCanvas.addLog("消息长度为小于等于0错误:" + iMsgLen);
            }
            if (msgId != 143) {
                Tools.printLog("iMsgLen" + iMsgLen + "msgId" + msgId);
            }
//            throw new Exception();
            return;
        }
        this.lStartReceiveTime = System.currentTimeMillis();
        //把消息类型 指令和消息体传给 数据处理类
        if (this.receiveData != null) {
            MainLogic.getInstance().netController.receiveResponse(this.receiveData, msgId, msgType);
            this.receiveData = null;
            bodyData = null;
        }
    }

    /**
     * 发送数据
     * @param netData byte[] 逻辑处理打包后的数据
     */
    public synchronized void send(byte[] sendData, int msgid) {
        //如果出于网络异常状态不执行
//          Tools.printLog("read send msg" + msgid);
        if (blUnUsed) {
            return;
        }
        //如果网络管理类消息线程未打开不执行
        if (!this.blInitNetManager) {
            return;
        }
        //如果发送数据包为空不执行
        if (sendData == null) {
            return;
        }
        //封装消息包
        ByteArrayOutputStream byOut = new ByteArrayOutputStream();
        if (Constant.bTestFlow) {//测试网络流量
            MainLogic.lFlowCount += byOut.size();
        }
        DataOutputStream dOut = new DataOutputStream(byOut);
        byte[] sendDataPackage = null;
        try {
            if (msgid == Constant.MSG_NET_CMD_SOCKET_START) {
                dOut.write(Constant.AUTH_CODE);
                dOut.write(Constant.AUTH_CODE2);
            } else {
                //写入消息体长度
                dOut.writeInt(sendData.length + 4);
                //写入消息体
                dOut.write(sendData);
            }
            dOut.flush();
            //组装消息包
            sendDataPackage = byOut.toByteArray();
            dOut.close();
            byOut.close();
            dOut = null;
            byOut = null;

        } catch (Exception ex) {
            if (Constant.DEBUG) {
                ex.printStackTrace();
                MainCanvas.addLog("send()封装消息体异常" + ex.toString());
            }
        }
        try {
            if (sendDataPackage != null) {
                this.sendOut.write(sendDataPackage);
                this.sendOut.flush();
                if (Constant.DEBUG) {
                    MainCanvas.addLog("send()" + msgid);
                }
                testMsid = msgid;
//                  Tools.printLog("have send msg" + msgid);
//                 Tools.printLog("消息已发出"+msgid);
                sendDataPackage = null;
            }
        } catch (Exception ex) {
            NetManager.blUnUsed = true;

            if (Constant.DEBUG && msgid != 300) {
                MainCanvas.addLog("send()发送消息ID:" + msgid);
            }
            Tools.printLog("send message erro exit!");
            if (Constant.DEBUG) {
                ex.printStackTrace();
            }
//            MainLogic.getInstance().exitGame();
            if (Constant.DEBUG) {
                MainCanvas.addLog("send()发送消息异常,准备断线重联");
            }
        }
    }
    /**
     * 网络消息收发线程
     */
    public static boolean blNetLogin = false;
    public static boolean blLoginNetV5 = false;
    public static byte blHaveSendLogin = -1;
    public static long blHaveSendStartTime = 0L;

    public void run() {
        // 网络连接之前休息5000毫秒, 如果前面的操作是断线的话, 用于清除缓冲的时间
        try {
            Thread.currentThread().sleep(500);
        } catch (Exception e) {
            if (Constant.DEBUG) {
                e.printStackTrace();
            }
        }

        this.lStartReceiveTime = System.currentTimeMillis();
        boolean blStart = createSendConnect(Constant.CONNECT_IP);
        Tools.printLog("建立连接成功");
        this.lStartReceiveTime = System.currentTimeMillis();
        if (blStart) {
            this.lStartReceiveTime = System.currentTimeMillis();
            try {
                Thread.currentThread().sleep(500);
            } catch (Exception e) {
                if (Constant.DEBUG) {
                    e.printStackTrace();
                }
            }
            if (!MainLogic.blLogined) {
                this.blInitNetManager = true;
                if (Constant.DEBUG) {
                    MainCanvas.addLog("发送登陆角色指令:" + Constant.MSG_NET_LOGIN_PLAYER);
                }
                Tools.printLog("net manager MSG_NET_CMD_LOGIN , exit");
                //#if USER_CENTER=="TRUE"
                if (Constant.QUICK_GAME == 2) {//快速进入
                    //发送登入游戏消息指令
                    Rms.loadGame(Constant.RMS_PLAYER_INDEX);
                    Rms.loadGame(Constant.RMS_PLAYER_LEVLE);
                    Rms.loadGame(Constant.RMS_PLAYER_SEX);
                    switch (Constant.PLAYER_INDEX) {
                        case 1:
                            Rms.loadGame(Constant.RMS_NEW_PLAYER_TUITION_1);
                            Rms.saveGame(Constant.RMS_NEW_PLAYER_TUITION_1, null);
                            break;
                        case 2:
                            Rms.loadGame(Constant.RMS_NEW_PLAYER_TUITION_2);
                            Rms.saveGame(Constant.RMS_NEW_PLAYER_TUITION_2, null);
                            break;
                        case 3:
                            Rms.loadGame(Constant.RMS_NEW_PLAYER_TUITION_3);
                            Rms.saveGame(Constant.RMS_NEW_PLAYER_TUITION_3, null);
                            break;
                        case 4:
                            Rms.loadGame(Constant.RMS_NEW_PLAYER_TUITION_4);
                            Rms.saveGame(Constant.RMS_NEW_PLAYER_TUITION_4, null);
                            break;
                    }
                    NetManager.blNetLogin = true;
//                    MainLogic.getInstance().send(Constant.MSG_NET_CMD_SOCKET_START, Constant.SOCKET_MSG_TYPE_LOGIC);//登陆上海的时候需要发
                    MainLogic.getInstance().send(Constant.MSG_NET_CMD_LOGIN, Constant.SOCKET_MSG_TYPE_LOGIC);
                    MainLogic.getInstance().uiInterFace.byMaxLoadingNum = (byte) 60;
                    MainLogic.getInstance().uiInterFace.setGameNextState(Constant.GAME_UI_ROAM);
                    MainLogic.pushState(Constant.GAME_UI_LOADING, false);
                    //等待一段时间，在发数据
                } else {
                    if (!blNetLogin) {//进入创建角色界面
                        blNetLogin = true;
                        MainLogic.getInstance().uiInterFace.byMaxLoadingNum = (byte) 60;
//                        MainLogic.getInstance().send(Constant.MSG_NET_CMD_SOCKET_START, Constant.SOCKET_MSG_TYPE_LOGIC);
                        MainLogic.getInstance().send(Constant.MSG_NET_CMD_LOGIN, Constant.SOCKET_MSG_TYPE_LOGIC);//发送登陆
                        MainLogic.getInstance().uiInterFace.setGameNextState(Constant.GAME_UI_CREATE_ROLE);//进入创建角色界面
                        MainLogic.pushState(Constant.GAME_UI_LOADING, false);
                    }
                }

                //#else
//#                 MainLogic.getInstance().send(Constant.MSG_NET_CMD_SOCKET_START, Constant.SOCKET_MSG_TYPE_LOGIC);
//#                 MainLogic.getInstance().send(Constant.MSG_NET_CMD_LOGIN, Constant.SOCKET_MSG_TYPE_LOGIC);
                //#endif
            } else {
                this.blInitNetManager = true;
                NetManager.blUnUsed = false;
                MainLogic.getInstance().send(Constant.MSG_NET_ENTER_WORLD, Constant.SOCKET_MSG_TYPE_LOGIC);
            }
        } else {
            return;
        }
        //读取网络响应
        while (!this.stopConnect) {
            try {
                if (this.blUnUsed == true) {
                    Tools.printLog("net manager run erro, exit");
                    NetManager.blUnUsed = true;
//                    MainLogic.getInstance().exitGame();
                    break;
                }
                this.receive2();
                //测试
//                long lTempTestTime = System.currentTimeMillis() - Constant.spacetime;
//                Tools.printLog("space time:"+lTempTestTime);
                Constant.spacetime = System.currentTimeMillis();
//                System.out.println("spacetime   ::::  " + MainCanvas.spacetime);
                //#if NOKIA_S40V3 || NORMAL_240_400 || MOTO || K790
//#                 Thread.sleep(100);
                //#else
                Thread.sleep(50);
                //#endif

            } catch (Exception ex) {
                if (Constant.DEBUG) {
                    ex.printStackTrace();
                }
                NetManager.blUnUsed = true;
//                MainLogic.getInstance().exitGame();
                if (Constant.DEBUG) {
                    MainCanvas.addLog("网络线程读取异常" + ex.toString());
                }
                if (Constant.DEBUG) {
                    ex.printStackTrace();
                }
            }
            if (this.blUnUsed == true) {
                return;
            }
        }
    }

    /******************************************************************************************
     *                                  建立短连接方式
     ******************************************************************************************/
    /**
     * 短连接方式建立socket
     * @param url String 连接ip
     * @param accountId int 帐号id
     * @param roleId int 角色id
     * @param sendData byte[] 发送数据包
     * @return boolean 是否操作正常
     */
    public void createShortConnect(String url, int accountId, int roleId, byte[] sendData) throws Exception {
        if (sendData == null) {
            return;
        }
        SocketConnection socket = null;
        DataInputStream dIn = null;
        DataOutputStream dOut = null;
        try {
            if (Constant.DEBUG) {
                MainCanvas.addLog("createShortConnect()建立中:" + url);
            }
            socket = (SocketConnection) Connector.open(url);
            socket.setSocketOption(SocketConnection.DELAY, Constant.SOCKET_DELAY);
            socket.setSocketOption(SocketConnection.KEEPALIVE, Constant.SOCKET_KEEPALIVE);
            socket.setSocketOption(SocketConnection.LINGER, Constant.SOCKET_LINGER);
            //#if NOKIA_S40V3 || NORMAL_240_400 || MOTO || K790
//#             socket.setSocketOption(SocketConnection.RCVBUF, 1024);
//# //              socket.setSocketOption(SocketConnection.SNDBUF, 512);
            //#else
            socket.setSocketOption(SocketConnection.RCVBUF, Constant.SOCKET_RCVBUF);
            socket.setSocketOption(SocketConnection.SNDBUF, Constant.SOCKET_SNDBUF);
            //#endif


            dIn = socket.openDataInputStream();
            dOut = socket.openDataOutputStream();
            if (Constant.DEBUG) {
                MainCanvas.addLog("createShortConnect()建立成功:");
            }
            //封装消息包
            ByteArrayOutputStream byOut = new ByteArrayOutputStream();
            DataOutputStream dOutData = new DataOutputStream(byOut);
            byte[] sendDataPackage = null;
            //写入消息头
            //写入帐号id
            dOutData.writeInt(accountId);
            //写入角色id
            dOutData.writeInt(roleId);
            //写入消息序号
            dOutData.writeInt(this.iNetMsgSerialNumber++);
            //写入消息体长度
            dOutData.writeInt(sendData.length);
            //写入消息体
            dOutData.write(sendData);
            dOutData.flush();
            //组装消息包
            sendDataPackage = byOut.toByteArray();
            dOutData.close();
            byOut.close();
            dOutData = null;
            byOut = null;
            //发送消息
            if (sendDataPackage != null) {
                dOut.write(sendDataPackage);
                dOut.flush();
                if (Constant.DEBUG) {
                    MainCanvas.addLog("createShortConnect()发送短连接消息：" + sendDataPackage.length + "字节");
                }
            } else {
                dIn.close();
                dIn = null;
                dOut.close();
                dOut = null;
                socket.close();
                socket = null;
            }

            if (Constant.DEBUG) {
                MainCanvas.addLog("createShortConnect()接收数据中:");
            }
            //读取消息
            int iCurPos = 0;
            byte[] headData = new byte[4];
            while (iCurPos < 4) {
                int len = dIn.read(headData, iCurPos, 4 - iCurPos);
                if (len > 0) {
                    iCurPos += len;
                }
            }
            int iMsgLen = (int) (((headData[0] & 0xff) << 24) | ((headData[1] & 0xff) << 16)
                    | ((headData[2] & 0xff) << 8) | (headData[3] & 0xff));
            if (iMsgLen > 0) {
                iCurPos = 0;
                byte[] bodyData = new byte[iMsgLen];
                while (iCurPos < iMsgLen) {
                    int len = dIn.read(bodyData, iCurPos, iMsgLen - iCurPos);
                    if (len > 0) {
                        iCurPos += len;
                    }
                }
                receiveData = bodyData;
                if (Constant.DEBUG) {
                    MainCanvas.addLog("读取网络消息包大小：" + receiveData.length + "字节");
                }
                if (receiveData != null) {
                    MainLogic.getInstance().netController.receiveResponse(receiveData, 0, (byte) 0);
                }
            }
            dIn.close();
            dIn = null;
            dOut.close();
            dOut = null;
            socket.close();
            socket = null;
        } catch (Exception ex) {
            if (Constant.DEBUG) {
                ex.printStackTrace();
            }
            if (Constant.DEBUG) {
                MainCanvas.addLog("createShortConnect()建立连接出错:" + ex.toString());
            }
            try {
                dIn.close();
                dIn = null;
                dOut.close();
                dOut = null;
                socket.close();
                socket = null;
            } catch (IOException ex1) {
                if (Constant.DEBUG) {
                    ex1.printStackTrace();
                }
            }
            throw ex;
        }
    }
}
